from django import forms
from django.shortcuts import render, redirect, HttpResponse
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

from mysite import models
from mysite.utills.pagenation import Pagination
from mysite.utills.bootstrap import BootStrapModelForm

def user_list(request):
    """用户管理"""
    # 获取用户列表
    queryset=models.UserInfo.objects.all()
    page_object = Pagination(request, queryset, page_size=2)

    # for obj in queryset:
    #     print(obj.id,obj.name,obj.age,obj.join_date.strftime('%Y-%m-%d'),obj.gender,obj.get_gender_display(),obj.depart_id,obj.depart.title)
        # obj.gender
        # get_字段名_display(),获取性别字段

        #obj.depart_id 数据库中存储的部门对应的值
        # obj.depart.title 根据id获取到depart对象
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request,'user_list.html', context)


def user_add(request):
    """添加用户"""
    if request.method == 'GET':
        context = {
            'gender_choice': models.UserInfo.gender_chioce,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    # 获取用户提交的数据
    name = request.POST.get('user')
    gender = request.POST.get('gd')
    password = request.POST.get('pwd')
    age = request.POST.get('age')
    salary = request.POST.get('sl')
    join_date = request.POST.get('ctime')
    depart = request.POST.get('dp')

    # 提交数据到数据库,depart_id=depart,需将传参的外键字段加上_id
    models.UserInfo.objects.create(
        name=name, gender=gender, password=password, age=age, salary=salary, join_date=join_date, depart_id=depart
    )
    return redirect('/user/list')


class UserModelForm(forms.ModelForm):

    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'gender', 'depart', 'salary', 'join_date']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环每个赋值属性form-control
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control'}
        # widgets = {
        #     'name': forms.TextInput(attrs={'class': 'form-control'}),
        #     'password': forms.PasswordInput(attrs={'class': 'form-control'}),
        #     'age': forms.TextInput(attrs={'class': 'form-control'}),
        #     'gender': forms.Select(attrs={'class': 'form-control'}),
        #     'depart': forms.Select(attrs={'class': 'form-control'}),
        #     'salary': forms.TextInput(attrs={'class': 'form-control'}),
        #     'join_date': forms.TextInput(attrs={'class': 'form-control'}),
        # }


def user_model_add(request):
    """基于modelForm添加用户"""
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user_model_add.html', {'form': form})
    # 用户post提交数据，校验
    form = UserModelForm(data=request.POST)
    # 如果成功，则存入库里
    if form.is_valid():
        form.save()
        return redirect('/user/list')
    # 校验失败
    return render(request, 'user_model_add.html', {'form': form})


def user_edit(request, nid):
    """编辑用户"""
    if request.method == 'GET':
        form = UserModelForm
        # 根据id获取编辑的那一行的数据
        row_object = models.UserInfo.objects.filter(id=nid).first()
        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    row_object = models.UserInfo.objects.filter(id=nid).first()
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/user/list')
    return render(request, 'user_edit.html', {'form': form})


def user_delete(request, nid):
    models.UserInfo.objects.filter(id=nid).first().delete()
    return redirect('/user/list')






































